package com.tavenli.repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.tavenli.entity.DeviceLogEntity;

@Repository
public class DeviceLogDao extends BaseDao{
	private static Logger logger = LoggerFactory.getLogger(UserDao.class);

	public DeviceLogEntity getDeviceLogEntityById(int id) {
		try {
			return this.getById(DeviceLogEntity.class, id);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	public int queryDataCount(Map<String, Object> paramMap) {
		StringBuilder hql = new StringBuilder();
		Map<String, Object> params = new HashMap<String, Object>();

		hql.append("select count(*) from DeviceLogEntity where 1=1");

		if (paramMap.get("id") != null) {
			hql.append(" and id=:id");
			params.put("id", paramMap.get("id"));
		}
		return super.queryPageTotalCount(hql.toString(), params).intValue();
	}

	public List<DeviceLogEntity> queryPageData(int start, int maxSize,
			Map<String, Object> paramMap) {
		StringBuilder hql = new StringBuilder();
		Map<String, Object> params = new HashMap<String, Object>();
		hql.append("from DeviceLogEntity  where 1=1");
		if (paramMap.get("id") != null) {
			hql.append(" and id=:id");
			params.put("id", paramMap.get("id"));
		}
		hql.append(" order by id desc");
		return super.queryPageList(hql.toString(), params, start, maxSize);
	}

	public int delDeviceLog(int deviceLogId) {
		String hql = "delete DeviceLogEntity t where t.id=?";
		Query query = this.getEntityManager().createQuery(hql);
		query.setParameter(1, deviceLogId);
		try {
			return query.executeUpdate();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return -1;
	}

	public int delDeviceLogs(Integer[] deviceLogIds) {

		String hql = "delete DeviceLogEntity t where t.id in ("
				+ StringUtils.join(deviceLogIds, ",") + ")";

		Query query = this.getEntityManager().createQuery(hql);

		try {
			return query.executeUpdate();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return -1;
	}
	/**
	 * 判断考勤记录是否在数据库中已经存在
	 * @param deviceLogEntity
	 * @return
	 */
	public boolean exist(DeviceLogEntity deviceLogEntity) {
		String hql = "select count(*) from DeviceLogEntity where deviceEventDate=? and sn=?";
		Query query = this.createQuery(hql);
		query.setParameter(1, deviceLogEntity.getDeviceEventDate());
		query.setParameter(2, deviceLogEntity.getSn());
		Object obj = query.getResultList().get(0);
		Long count = Long.parseLong(obj.toString());
		return count.compareTo(0L)>0;
	}
}
